<template>
  <el-tabs type="border-card">
    <el-tab-pane label="卖出">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item>
          <el-tag type="success">可用数量{{ volumeOfHold }}</el-tag>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="form.number"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sell">卖出</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="买入">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item>
          <el-tag type="success">可用金额{{ money }}</el-tag>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="form.number" number ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="buy">买入</el-button>

          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { myStock, buyStock, sellStock } from '@/api/order'
import { getUserInfo } from '@/api/login'

export default {
    name: 'exchange',
    props: ['id'],
    data() {
        return {
            form: {
                price: 5,
                number: 1,
            },
            volumeOfHold: 0,
            money: 0,
        }
    },
    methods: {
        fetchInfo() {
            myStock({ stock: this.id }).then((res) => {
                let rst = res.results.filter((item) => item.stock == this.id)
                if (rst.length == 1) {
                    this.volumeOfHold = rst[0].num_free
                }
            })
            getUserInfo().then((res) => {
                this.money = res.results[0].cny_free
            })
        },
        buy() {
            buyStock({ stock: this.stockId,
                type: 'false',
                price: this.form.price,
                undealed: this.form.number,
            }).then(res => {
                console.log(res)
                this.fetchInfo()
                this.$emit('refresh')
            })
        },
        sell() {
            sellStock({ stock: this.stockId,
                type: 'true',
                price: this.form.price,
                undealed: this.form.number,
            }).then(res => {
                console.log(res)
                this.fetchInfo()
                this.$emit('refresh')
            })
        },
    },
    computed: {
        stockId() {
            return parseInt(this.id, 10)
        },
    },
    mounted() {
        this.fetchInfo()
    },
}
</script>

<style>
</style>